package com.outfood.task;

import com.alibaba.fastjson.JSON;
import com.outfood.common.order.Details;
import com.outfood.common.pojo.MeiTOrderInfo;
import com.outfood.domain.Order;
import com.outfood.domain.Rule;
import com.outfood.domain.Store;
import com.outfood.service.IOrderService;
import com.outfood.service.IRuleService;
import com.outfood.service.IStoreService;
import com.outfood.service.impl.MeiTuanOperateServiceImpl;
import com.rys.common.enums.SearchTypeEnum;
import com.rys.common.utils.DateUtils;
import com.rys.common.utils.Search;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @Author huisonglin
 * @Description
 * @PackageName outfood-platform
 * @Package com.outfood.task
 * @Date 2024-03-25 17:08
 * @Version 1.0
 */
@Component
@Log4j2
public class ScanOrderTask {

    @Resource
    IStoreService storeService;
    @Resource
    MeiTuanOperateServiceImpl meiTuanOperateService;
    @Resource
    IOrderService orderService;
    @Resource
    IRuleService ruleService;


    @Scheduled(cron = "0 0/3 * * * ?")
    public void scan(){
        long start  = new Date().getTime();
        log.info("--------------------------------------------开始获取待出餐订单------------------------------------------------------------");
        List<Store> storeList = storeService.getList(new Search().add("storeStatus", SearchTypeEnum.EqualTo,"1").add("platform","MEITUAN").add("onlineStatus",SearchTypeEnum.EqualTo,"ONLINE"));
        storeList.forEach(store -> {
            try {
                if("FALSE".equals(store.getAutoOut())){
                    log.warn("{}没有开启自动出餐",store.getStoreName());
                    return;
                }
                MeiTuanOperateServiceImpl.Query query = new MeiTuanOperateServiceImpl.Query();
                query.setCookie(store.getCookie());
                query.setPageGray("1");
                query.setRegion_id(store.getRegionId());
                query.setRegion_version(store.getRegionVersion());
                query.setPageNum("1");
                query.setStoreId(store.getId());
                query.setPageSize("10");
                query.setTag("prepMeal");
                List<MeiTuanOperateServiceImpl.WmOrderList> orderList = meiTuanOperateService.getOrderList(query);
                Rule rule = ruleService.getList(new Search().add("storeId", SearchTypeEnum.EqualTo, store.getId())).get(0);
                orderList.forEach(orderItem ->{
                    Order order = new Order();
                    order.setOrderTime(new Date(orderItem.getCommonInfoObj().getOrder_time()*1000));
                    order.setTheoryOutTime(new Date(order.getOrderTime().getTime()+1000*60*rule.getTime()));
                    order.setConfirmTime(new Date(orderItem.getCommonInfoObj().getConfirmTime()*1000));
                    //order.setBuyerName(orderItem.get);
                    String foodName = "";
                    try {
                        for (Details detail : orderItem.getDetail().getFoodInfo().getCartDetailVos().get(0).getDetails()) {
                            foodName+=detail.getFoodName()+"、";
                        }
                    } catch (Exception e) {
                        try {
                            MeiTOrderInfo meiTOrderInfo = JSON.parseObject(orderItem.getOrderInfo(), MeiTOrderInfo.class);
                            foodName = meiTOrderInfo.getCartDetailVos().get(0).getDetails().get(0).getFood_name();
                        } catch (Exception ex) {
                            foodName = "...";
                        }

                    }
                    order.setFoodName(foodName);
                    try {
                        order.setIncome(orderItem.getDetail().getChargeInfo().getFixedSettlementInfo().getSettleAmount()+"");
                    } catch (Exception e) {
                        log.info(0);
                    }
                    order.setPoiId(orderItem.getCommonInfoObj().getWmPoiId()+"");
                    order.setOrderNo(orderItem.getCommonInfoObj().getWm_poi_order_dayseq()+"");
                    try {
                        order.setBuyerName(orderItem.getDetail().getUserInfo().getRecipientName());
                    } catch (Exception e) {
                        order.setBuyerName("未知");
                    }
                    order.setOrderSource("MEITUAN");
                    order.setOutStatus("READY");
                    order.setStoreId(store.getId());
                    try {
                        order.setRider(orderItem.getDetail().getLogisticsInfo().getTitle());
                    } catch (Exception e) {
                        order.setRider("未知");
                    }
                    order.setOutTradeNo(orderItem.getCommonInfoObj().getWm_order_id_view()+"");
//                    order.setInfo(JSON.toJSONString(orderItem));
                    List<Order> result = orderService.getList(new Search().add("outTradeNo", SearchTypeEnum.EqualTo, orderItem.getCommonInfoObj().getWm_order_id_view()));
                    if(CollectionUtils.isEmpty(result)){
                        orderService.add(order,"task");
                    }

                });
            } catch (Exception e) {
                log.error("获取订单失败",e);
            }

        });
        long end  = new Date().getTime();
        log.info("------------------------------------------获取待出餐订单结束共耗时{}ms------------------------------------------------------------",end-start);

    }

    public static void main(String[] args) {
        String a = "{\"activity\":[],\"address_latitude\":40068492,\"address_longitude\":116254585,\"agent_or_direct_poi\":1,\"appealInfo\":null,\"backup_privacy_phones\":[\"18601162240 转 0622\",\"13141326176 转 2676\"],\"bizTagSet\":[],\"boxPriceTotal\":0.0,\"cartCount\":1,\"cartDetailVos\":[{\"cartAmount\":9.3,\"cartName\":\"1号口袋\",\"details\":[{\"box_num\":0.0,\"box_price\":0.0,\"cart_id\":0,\"count\":1,\"countBak\":1,\"discountPoint\":\"6.5折\",\"discountRemark\":\"[6.5折,原价14.3]\",\"foodTagId\":0,\"foodTagName\":\"\",\"food_name\":\"苞谷臊子干拌面+饮料1个 （默认）\",\"food_price\":9.3,\"hasPackageDetails\":0,\"id\":5842148054156,\"locator_code\":null,\"origin_food_price\":14.3,\"packageDetail\":null,\"source_food_code\":null,\"tagWeight\":0,\"unit\":\"份\",\"upc_code\":null,\"wm_food_id\":14930231226}]}],\"completeOrderNotice\":\"\",\"confirm_time\":1715409932,\"currentSystemTime\":1715410081,\"delivery_btime\":0,\"delivery_btime_fmt\":\"\",\"discounts\":[{\"category\":0,\"hiddenType\":0,\"info\":\"-￥5.0\",\"type\":\"购买苞谷臊子干拌面+饮料1个原价14.3元现价9.3元\"}],\"encrypted\":0,\"estimateArrivalTime\":1715412269,\"estimate_arrival_time_fmt\":\"2024-05-11 15:24:29\",\"estimated_make_time\":480,\"expectPrefix\":\"立即送达\",\"expectSuffix\":\"前送达\",\"expectTimeFmt\":\"05-11 15:24\",\"has_been_invoiced\":0,\"hide_address_flag\":true,\"hide_flag\":true,\"id\":-1,\"insurance\":{\"claimDesc\":\"\",\"desc\":\"保障中\",\"effect\":1,\"name\":\"用户取消险\",\"status\":0},\"invoice_taxpayer_id\":\"\",\"invoice_title\":\"\",\"isBigOrder\":0,\"isPartRefundApply\":0,\"isShowDistanceAndAddress\":1,\"is_cross_day_pre_order\":0,\"is_display_bindedPhone\":false,\"is_poi_first_order\":false,\"is_pre_order\":0,\"is_use_privacy_phone\":true,\"jhsOrder\":false,\"logistics_code\":\"1005\",\"logistics_status\":15,\"mask_address\":false,\"mealFoodDoneVO\":null,\"need_tableware\":true,\"num\":48,\"orderBusiness\":0,\"orderCopyContent\":\"5月11日  #48号单#  山城小面（第1档口福临坊美食城店）  李先生  18400619053 转 5888    苞谷臊子干拌面+饮料1个 （默认） 1份  合计：9.3元  备注:顾客需要1份餐具； (已付款)  在线支付订单\",\"orderImValid\":1,\"orderTag\":0,\"orderType\":30,\"order_phone\":\"\",\"order_time\":1715409929,\"order_time_fmt\":\"2024-05-11 14:45:29\",\"package_bag_money\":0,\"part_refund_time_limit\":true,\"pay_status\":3,\"phfOrderVO\":{\"mainOrderVO\":{\"dayNo\":\"49\",\"orderViewID\":301067923893446222,\"orderViewIDStr\":\"301067923893446222\"},\"phfOrderAcceptHint\":\"#49 #48须同时接单,请在#49接单\",\"phfOrderTitle\":\"用户选择【帮拼友收餐】，须同时出餐和打包\",\"subOrderVOList\":[{\"dayNo\":\"48\",\"orderViewID\":2901067923340744500,\"orderViewIDStr\":\"2901067923340744500\"}]},\"pick_type\":0,\"poiPushDay\":20240511,\"poiUseSLA\":true,\"poi_city_id\":110100,\"poi_latitude\":40087731,\"poi_longitude\":116233894,\"poi_name\":\"山城小面（第1档口福临坊美食城店）\",\"preOrderFoodDoneVO\":{\"canClickLimitTime\":1715410052,\"clickWarningToast\":\"出餐时间过短暂不支持上报，请真实上报出餐时间\",\"preOrderGrayTag\":true},\"privacy_phone\":\"18400619053,5888\",\"privacy_phone_status\":0,\"recipient_address\":\"\",\"recipient_bindedPhone\":\"手机尾号1635\",\"recipient_name\":\"李先生\",\"recipient_phone\":\"手机尾号1635\",\"refundType\":-1,\"remark\":\"顾客需要1份餐具；\",\"selfDeliveryBackflowGray\":true,\"self_service\":0,\"serverTime\":1715410081,\"shippingCapacityCodes\":[],\"shipping_fee\":0.0,\"springFestivalServiceFee\":0.0,\"status\":4,\"tips\":[],\"total_after\":9.3,\"user_id\":3938483326,\"utime\":1715410074,\"wmUserId\":3938483326,\"wm_order_id_view\":2901067923340744500,\"wm_order_id_view_str\":\"2901067923340744500\",\"wm_order_pay_type\":2,\"wm_poi_id\":16428596,\"wm_poi_order_dayseq\":0}";
        MeiTOrderInfo meiTOrderInfo = JSON.parseObject(a, MeiTOrderInfo.class);
        String foodName = meiTOrderInfo.getCartDetailVos().get(0).getDetails().get(0).getFood_name();
        System.out.println(foodName);
    }

    @Scheduled(cron = "0/10 * * * * ? ")
    public void toOut(){
        long start  = new Date().getTime();
        log.info("------------------------------------------开始出餐------------------------------------------------------------");
        String time = DateUtils.getTime();
        List<Order> list = orderService.getList(new Search().add("orderSource","MEITUAN").add("outStatus", SearchTypeEnum.EqualTo, "READY").add("theoryOutTime",SearchTypeEnum.LessThanOrEqual,time));
        list.forEach(order -> {
            try {
                MeiTuanOperateServiceImpl.Query query = new MeiTuanOperateServiceImpl.Query();
                query.setStoreId(order.getStoreId());
                Store store = storeService.get(order.getStoreId());
                query.setCookie(store.getCookie());
                query.setRegion_version(store.getRegionVersion());
                query.setOrderId(order.getId());
                query.setRegion_id(store.getRegionId());
                MeiTuanOperateServiceImpl.Result result = meiTuanOperateService.excuteOutFood(query);
                log.info(result);
                if(result.getCode() == 0){
                    order.setOutStatus("OUTED");
                    order.setOutFoodTime(new Date());
                    orderService.update(order.getId(),order,"task");
                }else{
                    order.setOutStatus("EXCEPT");
                    orderService.update(order.getId(),order,"task");
                }
            } catch (Exception e) {
                log.error("",e);
            }
        });
        long end  = new Date().getTime();
        log.info("------------------------------------------出餐结束共耗时{}ms------------------------------------------------------------",end-start);
    }


}
